package com.jinxinol.core.common;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.jinxinol.basic.system.service.LogAspect;

public class BusinessLogFilter implements Filter {

	// 线程安全
	public static final ThreadLocal<HttpServletRequest> http = new ThreadLocal<HttpServletRequest>();

	public void init(FilterConfig config) {
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws ServletException, IOException {
		
		HttpServletRequest req = (HttpServletRequest) request;
		LogAspect log = null;
		String busyUrl = req.getRequestURI();
		if(busyUrl.endsWith(".do")||busyUrl.endsWith(".action")){
			String methodName = busyUrl.substring(busyUrl.lastIndexOf("/")+1, busyUrl.lastIndexOf("."));
			if (methodName.contains("_")){
				methodName = methodName.substring(methodName.lastIndexOf("_"));
			}
			long time = System.currentTimeMillis();
			try {
				log = (LogAspect) ContextHelper.getBean("LogAspect");
				chain.doFilter(request, response);
				try{
				log.wirteSuccLog(req, methodName, busyUrl, time);
				}catch (Exception e) {
					e.printStackTrace();
				}
			} catch (Exception e) {
				log.wirteFailLog(req, methodName, busyUrl, time, e);
				e.printStackTrace();
			}
		}else{
			chain.doFilter(request, response);
		}
	}
}
